package com.slkj.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.slkj.dto.Result;
import com.slkj.dto.SpecialTaskDTO;
import com.slkj.dto.StatusCode;
import com.slkj.entity.File;
import com.slkj.entity.LeaderIdea;
import com.slkj.entity.SpecialTask;
import com.slkj.service.SpecialService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.csource.common.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName SpecialController.java
 * @Description TODO
 * @createTime 2020年03月12日 11:18:00
 */
@Transactional
@RestController
@CrossOrigin
@RequestMapping("${address.prefix}/special")
public class SpecialController {


    private Logger log = LoggerFactory.getLogger(SpecialController.class);

    @Autowired
    private SpecialService specialService;


    @PostMapping("/createTask")
    public Result createTask(@RequestBody SpecialTask specialTask) {

        log.info("----------------------->>>createTask(@RequestBody SpecialTask specialTask) ");
        if (specialTask == null) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }

        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");


        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        specialService.createTask(specialTask, username);

        return new Result(true, StatusCode.OK, "success");
    }

    @PostMapping("/taskUpload")
    public Result taskUpload(@RequestBody String data) throws IOException, MyException {
        log.info("----------------------->>>taskUpload(@RequestParam(value = \"file\") MultipartFile multipartFile)");

        JSONObject jsonObject = JSONObject.parseObject(data);
        List<File> fileList = JSONObject.parseArray(jsonObject.getString("file"), File.class);
        System.out.println(fileList.toString());
        String dutyId = jsonObject.getString("dutyId");
        String type = jsonObject.getString("type");
        String count = jsonObject.getString("count");
        List<Map> variables = JSONObject.parseArray(jsonObject.getString("variables"), Map.class);

//        String dutyId = multipartHttpServletRequest.getParameter("dutyId");
//        MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");


        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        log.info("----------------------->>>获取参数dutyId=" + dutyId);

        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }


        specialService.taskUpload(fileList, username, dutyId, type, variables, count);

        return new Result(true, StatusCode.OK, "success");
    }

    @PostMapping("/passTask")
    public Result passTask(@RequestBody String data) {
        log.info("----------------------->>>passTask(@RequestBody String data)");

        JSONObject jsonObject = JSONObject.parseObject(data);
        String count = jsonObject.getString("count");
        List<Map> variables = JSONObject.parseArray(jsonObject.getString("variables"), Map.class);

        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");

        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }
        String specialAuditIdea = jsonObject.getString("specialAuditIdea");


        if (StringUtils.isBlank(specialAuditIdea)) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }

        boolean statusCheck = statusCheck(variables);
        if (!statusCheck) {
            return new Result(false, StatusCode.ERROR, "参数异常");
        }
        List<String> dutyIdList = JSONObject.parseArray(jsonObject.getString("dutyId"), String.class);


        specialService.passTask(dutyIdList, variables, count, specialAuditIdea);

        return new Result(true, StatusCode.OK, "success");
    }


    @PostMapping("/noPassTask")
    public Result noPassTask(@RequestBody String data) {
        log.info("----------------------->>>noPassTask(@RequestBody String data) ");

        JSONObject jsonObject = JSONObject.parseObject(data);
        String count = jsonObject.getString("count");
        List<Map> variables = JSONObject.parseArray(jsonObject.getString("variables"), Map.class);


        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");

        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        boolean statusCheck = statusCheck(variables);
        if (!statusCheck) {
            return new Result(false, StatusCode.ERROR, "参数异常");
        }
        List<String> dutyIdList = JSONObject.parseArray(jsonObject.getString("dutyId"), String.class);

        String specialAuditIdea = jsonObject.getString("specialAuditIdea");


        if (StringUtils.isBlank(specialAuditIdea)) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }

        log.info("----------------------->>>获取参数specialAuditIdea=" + specialAuditIdea);

        specialService.noPassTask(dutyIdList, variables, count, specialAuditIdea);

        return new Result(true, StatusCode.OK, "success");
    }

    @PostMapping("/getTaskFeedback")
    public Result getTaskFeedback(@RequestBody String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        String specialTitle = jsonObject.getString("title");
        String specialIndexSource = jsonObject.getString("indexSource");
        String specialLight = jsonObject.getString("light");
        String status = jsonObject.getString("status");

        if (StringUtils.isNotBlank(status)) {
            status = "通过";
        }


        Date beginDate = null;
        Date endDate = null;

        if (StringUtils.isNotBlank(jsonObject.getString("projectTime"))) {
            List<String> projectTime = JSONObject.parseArray(jsonObject.getString("projectTime"), String.class);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            try {
                beginDate = simpleDateFormat.parse(projectTime.get(0));
                endDate = simpleDateFormat.parse(projectTime.get(1));
            } catch (ParseException e) {
                return new Result(false, StatusCode.ERROR, "日期格式转换异常");
            }
        } else if (StringUtils.isNotBlank(jsonObject.getString("month"))) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            try {
                beginDate = simpleDateFormat.parse(jsonObject.getString("month") + "/01");
                endDate = simpleDateFormat.parse(jsonObject.getString("month") + "/31");
            } catch (ParseException e) {
                return new Result(false, StatusCode.ERROR, "日期格式转换异常");
            }

        }
        String submitUnit = jsonObject.getString("userId");
        String leader = jsonObject.getString("leader");
        String gotoPageString = jsonObject.getString("page");
        String pageSizeString = jsonObject.getString("pageSize");

        log.info("---------------------------------------------->>>>>>>>获取specialTitle=" + specialTitle);
        log.info("---------------------------------------------->>>>>>>>获取specialIndexSource=" + specialIndexSource);
        log.info("---------------------------------------------->>>>>>>>获取beginDate=" + beginDate + toString());
        log.info("---------------------------------------------->>>>>>>>获取specialLight=" + specialLight);
        log.info("---------------------------------------------->>>>>>>>获取submitUnit=" + submitUnit);
        log.info("---------------------------------------------->>>>>>>>获取endDate=" + endDate + toString());
        log.info("---------------------------------------------->>>>>>>>获取leader=" + leader);
        log.info("---------------------------------------------->>>>>>>>获取gotoPageString=" + gotoPageString);
        log.info("---------------------------------------------->>>>>>>>获取pageSizeString=" + pageSizeString);


        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");


        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }
        int gotoPage = 1;

        if (StringUtils.isNotBlank(gotoPageString) && StringUtils.isNumeric(gotoPageString)) {
            gotoPage = Integer.parseInt(gotoPageString);
        }

        int pageSize = 10;

        if (StringUtils.isNotBlank(pageSizeString) && StringUtils.isNumeric(pageSizeString)) {
            pageSize = Integer.parseInt(pageSizeString);
        }


        PageInfo<SpecialTaskDTO> pageInfo = specialService.getTaskFeedback(specialTitle, specialIndexSource, beginDate, endDate
                , specialLight, username, gotoPage, pageSize, submitUnit, leader, status);


        if (pageInfo == null) {
            log.error("查询专项行动反馈,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }

        if (pageInfo.getSize() == 0) {
            log.error("查询专项行动反馈,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }
        return new Result(true, StatusCode.OK, "查询成功", pageInfo);
    }

    @PostMapping("/lightAdjust")
    public Result lightAdjust(@RequestBody String data) {
        log.info("----------------------->>>lightAdjust(@RequestBody String data)");

        JSONObject jsonObject = JSONObject.parseObject(data);

        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        String count = jsonObject.getString("count");
        List<Map> variables = JSONObject.parseArray(jsonObject.getString("variables"), Map.class);


        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }
        boolean statusCheck = statusCheck(variables);
        if (!statusCheck) {
            return new Result(false, StatusCode.ERROR, "参数异常");
        }
        List<String> dutyIdList = JSONObject.parseArray(jsonObject.getString("dutyId"), String.class);

        String light = jsonObject.getString("light");
        String lightCause = jsonObject.getString("lightCause");

        log.info("----------------------->>>获取参数light=" + light);
        if (dutyIdList == null || StringUtils.isBlank(light) || StringUtils.isBlank(lightCause)) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }

        specialService.lightAdjust(dutyIdList, light, variables, count, lightCause);

        return new Result(true, StatusCode.OK, "success");
    }

    @PostMapping("/getLeaderIdea")
    public Result getLeaderIdea(@RequestBody String data) {
        log.info("----------------------->>>lightAdjust(@RequestBody String data)");

        JSONObject jsonObject = JSONObject.parseObject(data);

        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");


        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }
        String dutyId = jsonObject.getString("dutyId");

        log.info("----------------------->>>获取参数dutyId=" + dutyId);
        if (StringUtils.isBlank(dutyId)) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }

        if (!StringUtils.isNumeric(dutyId)) {
            return new Result(false, StatusCode.ERROR, "参数格式有误");
        }

        List<LeaderIdea> leaderIdeaList = specialService.getLeaderIdea(dutyId);

        if (leaderIdeaList == null) {
            log.error("查询领导批示数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }
        if (leaderIdeaList.size() == 0) {
            log.error("查询领导批示数据,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }


        log.info("查询领导批示数据,返回View");
        return new Result(true, StatusCode.OK, "查询领导批示数据成功", leaderIdeaList);

    }


    private boolean statusCheck(List<Map> mapList) {
        boolean result = false;
        if (mapList != null && mapList.size() != 0) {
            for (Map map : mapList) {
                String[] checkSourceArray = new String[]{"通过", "待审核", "未通过待上传", "不合格"};
                label:
                for (String s : checkSourceArray) {
                    Iterator iterator = map.keySet().iterator();
                    while (iterator.hasNext()) {
                        if (map.get(iterator.next()).equals(s)) {
                            result = true;
                            break label;
                        }
                    }
                }
            }

        }
        return result;
    }
}
